﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArcEngine.CourseDesign.Win.Util
{
    public static class MapHelper
    {
        /// <summary>
        /// 加载矢量数据
        /// </summary>
        public static IFeatureLayer LoadShp(string shpFileFullName)
        {
            if (string.IsNullOrEmpty(shpFileFullName) || string.IsNullOrWhiteSpace(shpFileFullName))
            {
                return null;
            }

            string fileDir = System.IO.Path.GetDirectoryName(shpFileFullName);
            string fileName = System.IO.Path.GetFileName(shpFileFullName);
            // 实例化ShapefileWorkspaceFactory工作空间，打开Shape文件
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(fileDir, 0);
            // 创建并实例化要素集
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName);
            IFeatureLayer featureLayer = new FeatureLayer
            {
                FeatureClass = featureClass
            };
            featureLayer.Name = featureLayer.FeatureClass.AliasName;
            return featureLayer;
        }

        /// <summary>
        /// 加载栅格数据
        /// </summary>
        public static IRasterLayer LoadRaster(string rasterFileFullName)
        {
            if (string.IsNullOrEmpty(rasterFileFullName) || string.IsNullOrWhiteSpace(rasterFileFullName))
            {
                return null;
            }

            string fileDir = System.IO.Path.GetDirectoryName(rasterFileFullName);
            string fileName = System.IO.Path.GetFileName(rasterFileFullName);
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactory();
            IWorkspace workspace = workspaceFactory.OpenFromFile(fileDir, 0);
            IRasterWorkspace rasterWorkspace = workspace as IRasterWorkspace;
            IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(fileName);
            // 影像金字塔判断与创建
            if (rasterDataset is IRasterPyramid3 rasterPyramid3)
            {
                if (!rasterPyramid3.Present)
                {
                    rasterPyramid3.Create(); // 创建金字塔
                }
            }
            IRaster raster = rasterDataset.CreateDefaultRaster();
            IRasterLayer rasterLayer = new RasterLayerClass();
            rasterLayer.CreateFromRaster(raster);
            return rasterLayer;
        }

        /// <summary>
        /// 获取地图单位
        /// </summary>
        public static string GetMapUnit(this AxMapControl axMapControl)
        {
            esriUnits esriMapUnit = axMapControl.Map.MapUnits;
            string mapUnit = string.Empty;
            switch (esriMapUnit)
            {
                case esriUnits.esriCentimeters:
                    mapUnit = "厘米";
                    break;
                case esriUnits.esriDecimalDegrees:
                    mapUnit = "十进制";
                    break;
                case esriUnits.esriDecimeters:
                    mapUnit = "分米";
                    break;
                case esriUnits.esriFeet:
                    mapUnit = "尺";
                    break;
                case esriUnits.esriInches:
                    mapUnit = "英寸";
                    break;
                case esriUnits.esriKilometers:
                    mapUnit = "千米";
                    break;
                case esriUnits.esriMeters:
                    mapUnit = "米";
                    break;
                case esriUnits.esriMiles:
                    mapUnit = "英里";
                    break;
                case esriUnits.esriMillimeters:
                    mapUnit = "毫米";
                    break;
                case esriUnits.esriNauticalMiles:
                    mapUnit = "海里";
                    break;
                case esriUnits.esriPoints:
                    mapUnit = "点";
                    break;
                case esriUnits.esriUnitsLast:
                    mapUnit = "UnitsLast";
                    break;
                case esriUnits.esriUnknownUnits:
                    mapUnit = "未知单位";
                    break;
                case esriUnits.esriYards:
                    mapUnit = "码";
                    break;
                default:
                    break;
            }
            return mapUnit;
        }

        /// <summary>
        /// 根据图层名称获取矢量数据类型的图层数据
        /// </summary>
        public static IFeatureLayer GetShpFeatureLayerByName(this AxMapControl axMapControl, string featureLayerName)
        {
            return GetTFeatureLayerByName<IFeatureLayer>(axMapControl, featureLayerName);
        }

        /// <summary>
        /// 根据图层名称获取图层索引
        /// </summary>
        public static IRasterLayer GetRatserFeatureLayerByName(this AxMapControl axMapControl, string featureLayerName)
        {
            return GetTFeatureLayerByName<IRasterLayer>(axMapControl, featureLayerName);
        }

        private static T GetTFeatureLayerByName<T>(this AxMapControl axMapControl, string featureLayerName)
            where T : class, ILayer
        {
            T layer = null;
            for (int i = 0; i < axMapControl.LayerCount; i++)
            {
                if (featureLayerName.Equals(axMapControl.get_Layer(i).Name))
                {
                    layer = axMapControl.get_Layer(i) as T;
                    break;
                }
            }
            return layer;
        }

        /// <summary>
        /// 将点集保存为Shp
        /// </summary>
        public static void SaveAsShp(this IPointCollection pointCollection, string fileFullPath, ISpatialReference reference)
        {
            // 利用IWorkspaceFactory打开工做空间
            string fileDir = System.IO.Path.GetDirectoryName(fileFullPath);
            string fielName = System.IO.Path.GetFileName(fileFullPath);
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspaceFactory.OpenFromFile(fileDir, 0);

            // 创建字段编辑所需要的接口
            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            // 给字段属性、类型赋值
            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit)field;
            fieldEdit.Name_2 = "Shape";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            IGeometryDef geometryDef = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            // 设置坐标系
            geometryDefEdit.SpatialReference_2 = reference;
            fieldEdit.GeometryDef_2 = geometryDef;
            fieldsEdit.AddField(field);

            IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(fielName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", string.Empty);

            for (int j = 0; j < pointCollection.PointCount; j++)
            {
                IPoint point = pointCollection.get_Point(j);
                IFeature feature = featureClass.CreateFeature();
                feature.Shape = point;
                feature.Store();
            }
        }
    }
}
